<template>
  <div class="page-miH page-bgBack">
    <PageHeader :backLock="false">
      <span>供应商字段设置</span>
    </PageHeader>
    <a-collapse :bordered="false" v-model="activeKey" class="p24 collapse" style="padding-top: 0" expand-icon-position="right">
      <a-collapse-panel v-for="(item, index) in fieldData" :key="String(index + 1)" style="margin-bottom: 24px">
        <div slot="header" class="pv12">
          <div class="firld_title">{{ item.moduleName }}</div>
        </div>
        <!-- 字段头 -->
        <a-row type="flex">
          <a-col :span="6">
            <div class="ta-center firld_header custom textleft">字段名称</div>
          </a-col>
          <a-col :span="2">
            <div class="ta-center firld_header custom">是否必填</div>
          </a-col>
          <a-col :span="4">
            <div class="ta-center firld_header custom">是否开启</div>
          </a-col>
          <a-col :span="6">
            <div class="ta-center firld_header custom border-left textleft">字段名称</div>
          </a-col>
          <a-col :span="2">
            <div class="ta-center firld_header custom">是否必填</div>
          </a-col>
          <a-col :span="4">
            <div class="ta-center firld_header custom">是否开启</div>
          </a-col>
        </a-row>

        <!-- 字段start -->
        <a-row type="flex">
          <!-- 预制字段start -->
          <a-col :span="12" type="flex" v-for="(items, indexs) in item.formGroupFieldList" :key="indexs">
            <div class="border-bottom" :class="(indexs + 1) % 2 == 0 ? '' : 'border-right'">
              <a-row>
                <a-col :span="12">
                  <div class="ta-center firld_body dsy_body textleft">{{ items.fieldName }}</div>
                </a-col>
                <a-col :span="4">
                  <div class="ta-center firld_body dsy_body">
                    <a-checkbox :checked="items.isNecessary" @change="remoteControl(items, 'isNecessary')" />
                  </div>
                </a-col>
                <a-col :span="8">
                  <div class="ta-center firld_body dsy_body" style="position: relative">
                    <a-checkbox :checked="items.isOpen" @change="remoteControl(items, 'isOpen')" class="mx20" />
                    <div v-if="items.fieldSource === 2" class="mx20" style="position: absolute; right: 5px; top: 0">
                      <a-space size="middle">
                        <a-tooltip placement="top" :title="`修改字段【${items.fieldName}】`">
                          <a-icon type="form" class="pointer" @click="edit(items)" />
                        </a-tooltip>
                        <a-popconfirm :title="`确定删除字段【${items.fieldName}】吗？`" @confirm="confirmDelete(items)">
                          <a-icon type="delete" class="pointer" />
                        </a-popconfirm>
                      </a-space>
                    </div>
                  </div>
                </a-col>
              </a-row>
            </div>
          </a-col>

          <!-- 自定义字段end -->

          <a-col :span="12" type="flex">
            <div class="border-bottom" :class="item.formGroupFieldList.length % 2 == 0 ? 'border-right' : ''">
              <a-row>
                <a-col :span="24">
                  <div class="dsy_body">
                    <a-button type="link" icon="plus-circle" @click="addField(item)">添加字段</a-button>
                  </div>
                </a-col>
              </a-row>
            </div>
          </a-col>
        </a-row>
        <!-- 字段end -->
        <div style="height: 15px"></div>
      </a-collapse-panel>
    </a-collapse>
    <!-- 新增编辑 -->
    <a-modal :title="title" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
      <a-form-model ref="ruleForm" class="ruleFormShowStyle" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item
          help="1-20个字符，不能与现有字段重复"
          ref="fieldName"
          :rules="[
            {
              required: true,
              message: '请输入字段名称'
            }
          ]"
          label="字段名称"
          prop="fieldName"
        >
          <a-input allowClear v-model="form.fieldName" placeholder="请输入字段名称" :max-length="20" />
        </a-form-model-item>
        <a-form-model-item
          ref="fieldType"
          :rules="{
            required: true,
            message: '请选择字段类型'
          }"
          label="字段类型"
          prop="fieldType"
        >
          <a-select
            allowClear
            :disabled="marking === 2 ? true : false"
            v-model="form.fieldType"
            placeholder="请选择字段类型"
            style="width: 100%"
            @change="fieldTypeChange"
          >
            <a-select-option :value="item.k" v-for="item in fieldTypeArr" :key="item.k">{{ item.v }}</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="选项值" v-if="form.fieldType == '1'" :label-col="{ span: 5 }" :wrapper-col="{ span: 22 }">
          <div
            v-for="(item, index) in form.options"
            :key="index"
            class="display-flex"
            style="align-items: center; width: 80%; margin: 0 auto"
          >
            <div style="width: 120px">{{ `选项 ${index}` }}</div>
            <a-input allowClear v-model="form.options[index]" placeholder="请输入字段名称" :max-length="15" />
            <a-icon
              style="margin: 0 15px"
              v-if="form.options.length > 1"
              class="dynamic-delete-button pointer"
              type="delete"
              :disabled="form.options.length === 1"
              @click="remove(index)"
            />
          </div>
          <div style="text-align: center">
            <a-button type="dashed" style="width: 60%" @click="addDomain"> <a-icon type="plus" />添加自定义选项 </a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { findFormGysReq, findFormGysDeleteReq, findFormGysUpdateReq, findFormGysCreateReq } from "./api";
const fieldTypeArr = [
  { k: 1, v: "下拉选择器" },
  { k: 2, v: "单行输入框" },
  { k: 3, v: "日期选择器" },
  { k: 4, v: "多行输入框" },
  { k: 5, v: "数字输入框" },
  { k: 6, v: "地区选择器" },
  { k: 7, v: "文件/图片上传" },
  { k: 8, v: "日期区间" },
  { k: 9, v: "地区选择+详细地址" },
  { k: 10, v: "手机号输入框" },
  { k: 11, v: "邮箱输入框" }
];

export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,
      type: "",
      fieldData: [],
      activeKey: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      form: {
        options: []
      },
      marking: null,
      moduleCode: "",
      moduleName: "",
      title: "",
      fieldTypeArr
    };
  },
  created() {
    this.type = this.$route.params.type;
    this.getListForPc();
  },
  methods: {
    fieldTypeChange(index) {
      if (index === 1) {
        this.form.options = [""];
      } else {
        this.form.options = null;
      }
    },
    edit(data) {
      this.form = JSON.parse(JSON.stringify(data));
      if (this.form.fieldType === 1) {
        this.form.options = this.form.options.split(",");
      }

      this.marking = 2;
      this.title = "编辑字段";
      this.visible = true;
    },
    checkbox() {},
    remove(index) {
      this.form.options.splice(index, 1);
    },
    addDomain() {
      this.form.options.push("");
    },
    addField(data) {
      this.dataSort = data.formGroupFieldList.length + 1;
      this.moduleCode = data.moduleCode;
      this.moduleName = data.moduleName;
      this.marking = 1;
      this.title = "添加字段";
      this.visible = true;
    },
    showModal() {
      this.visible = true;
    },
    handleOk(e) {
      this.confirmLoading = true;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const _form = JSON.parse(JSON.stringify(this.form));
          let flag = false;
          if (this.form.fieldType === 1) {
            _form.options.forEach((item, index) => {
              if (item === "") {
                flag = true;
              }
            });
          }

          if (this.marking === 1) {
            if (flag) {
              this.$notification["error"]({
                message: "error",
                description: "自定义选项不能为空，添加失败"
              });
              return;
            } else {
              if (_form.fieldType === 1) {
                _form.options = _form.options.join(",");
              }
              findFormGysCreateReq({
                moduleCode: this.moduleCode,
                moduleName: this.moduleName,
                fieldSource: 2,
                sort: this.dataSort,
                isOpen: true,
                ..._form
              })
                .then((res) => {
                  this.$refs.ruleForm.resetFields();
                  this.form = {
                    options: []
                  };
                  this.visible = false;
                  this.getListForPc();
                  this.$message.success("添加成功!");
                })
                .catch((err) => {
                  console.log("debug log --> ", err);
                });
            }
          } else {
            if (_form.fieldType === 1) {
              _form.options = _form.options.join(",");
            }
            findFormGysUpdateReq(_form)
              .then((res) => {
                this.$refs.ruleForm.resetFields();
                this.form = {
                  options: []
                };
                this.visible = false;
                this.getListForPc();
                this.$message.success("修改成功!");
              })
              .catch((err) => {
                console.log("debug log --> ", err);
              });
          }
        } else {
          return false;
        }
      });
      this.confirmLoading = false;
    },
    handleCancel(e) {
      this.$refs.ruleForm.resetFields();
      this.form = {
        options: []
      };
      this.visible = false;
    },
    remoteControl(data, field) {
      findFormGysUpdateReq({
        ...data,
        [`${field}`]: !!!data[field]
      })
        .then((res) => {
          this.$message.success("修改成功!");
          this.getListForPc();
        })
        .catch((err) => {
          this.$message.error("修改失败!");
          console.log("debug log --> ", err);
        });
    },
    // 删除字段
    confirmDelete(item) {
      findFormGysDeleteReq(item.id)
        .then((res) => {
          this.$message.success(`确定删除字段【${item.fieldName}】成功！`);
          this.getListForPc();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    getListForPc() {
      findFormGysReq()
        .then((res) => {
          this.fieldData = res.data;
          res.data.forEach((element, index) => {
            this.activeKey.push(String(index + 1));
          });
        })
        .catch((err) => {
          this.$message.error("失败!");
          console.log("debug log --> ", err);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.collapse {
  background-color: #ffffff !important;
}
.textleft {
  text-align: left;
  padding-left: 24px;
}
</style>
<style lang="scss">
.ruleFormShowStyle {
  label {
    font-weight: 400;
  }
  .ant-form-explain {
    font-size: 12px;
  }
}
</style>
